﻿using Lan.Infrastructure.CameraOnvif;
using Lan.ServiceCore.Services;
using Model;
using System.Collections.Concurrent;

namespace Lan.ServiceCore.Onvif
{
    public class OnvifManage
    {
        ConcurrentDictionary<string, ONVIF_COMMON_INFO> _dictONVIF_COMMON_INFO;


        public static List<OnvifManage_COMMON_INFO> _common = new List<OnvifManage_COMMON_INFO>();


        private static OnvifManage _instance = null;

        public List<OnvifManage_COMMON_INFO> Common
        {
            get { return _common; }
            set { _common = value; }
        }

        public static void Init()
        {
            if (_common.Count > 0)
            {
                _common = new List<OnvifManage_COMMON_INFO>();

                _instance = null;
            }

            if (_instance == null)
                _instance = new OnvifManage();

            if (OnvifManage._common.Count <= 0)
            {
                _instance = new OnvifManage();
            }
        }

        OnvifManage_COMMON_INFO common = new OnvifManage_COMMON_INFO();

        ONVIF_MANAGEMENT_CAPABILITIES capabilities = new ONVIF_MANAGEMENT_CAPABILITIES();

        private OnvifManage()
        {
            _dictONVIF_COMMON_INFO = LoadONVIF_COMMONFromDatabase();

        }

        private ConcurrentDictionary<string, ONVIF_COMMON_INFO> LoadONVIF_COMMONFromDatabase()
        {
            CameraService cameraService = new CameraService();
            List<CameraModel> listCamera = cameraService.GetAllList();

            Dictionary<string, ONVIF_COMMON_INFO> dic;

            if (listCamera == null)
                dic = new Dictionary<string, ONVIF_COMMON_INFO>();
            else
            {
                dic = new Dictionary<string, ONVIF_COMMON_INFO>(10);
                foreach (var v in listCamera)
                {
                    if (!string.IsNullOrEmpty(v.CameraURL))
                    {
                        int ret = onvifsdk.ONVIF_MAGEMENT_GetCapabilitiesEx(20, v.Ip, 80, v.Username, v.Password, ref capabilities);
                        if (ret == 0)
                        {
                            common.ip = v.Ip;
                            common.COMMON_INFO.username = v.Username;
                            common.COMMON_INFO.password = v.Password;
                            common.COMMON_INFO.onvifUrls = capabilities.onvifUrls;
                            dic[v.Ip] = common.COMMON_INFO;
                            _common.Add(common);
                        }
                    }
                }
            }
            return new ConcurrentDictionary<string, ONVIF_COMMON_INFO>(dic);
        }

    }
}
